const express = require("express");
const router = express.Router();
const md5 = require("md5-node");
const db = require("../db.js");
const multiparty = require("multiparty");

// 登录相关
router.get("/login", function (req, res, next) { // 访问登录页
    res.render("login.ejs");
});

router.post("/doLogin", function (req, res, next) { // 登录提交后，验证账号
    const userName = req.body.username;
    const pas = md5(req.body.password);
    var sql = 'SELECT * FROM admin where user_name=? and password=?';
    let sqlParam = [userName, pas];
    // 根据用户输入进行查询
    db.conn.query(sql, sqlParam, function (err, result) {
        if (err) {
            console.log('[SELECT ERROR] - ', err.message);
            return;
        }
        if (result && result.length > 0) { // 若输入账号正确，在表中会查到记录
            // 使用 session 来保存登录人信息，用于权限控制
            req.session.userInfo = result[0];
            // 在路由文件中设置全局变量 userInfo，保存已登录的用户名，这样在所有页面都可显示登录用户信息
            // 在其他 ejs 模板文件中直接使用<%=userInfo%>调用该全局变量
            req.app.locals["userInfo"] = req.session.userInfo.user_name;
            res.redirect("/admin/product"); // 跳转到 product 页面
        } else {
            res.send("<script>alert('登录失败');location.href='/admin/login';</script>");
        }
    });
});

// 退出登录
router.get("/logout", function (req, res, next) {
    req.session.destroy(function (err) { // 销毁 Session 信息
        if (err) {
            console.log(err);
        } else {
            res.redirect("/admin/login");
        }
    });
});

router.get('/product', function (req, res, next) {
  // 查询产品总记录数
  var sumSQL = "select count(*) as recordCount from product";
  db.conn.query(sumSQL, function (err, result) {
    if (err) {
      console.log(err);
      return;
    }
    var recordCount = result[0].recordCount;
    var pageSize = 3;
    var pageCount = Math.ceil(recordCount / pageSize);
    var page = req.query.page || 1;
    var start = (page - 1) * pageSize;
    var strSQL = "select * from product order by id desc limit " + start + "," + pageSize;
    db.conn.query(strSQL, function (err, result) {
      if (err) {
        console.log('[SELECT ERROR] - ', err.message);
        return;
      }
      res.render("product/index", { list: result, yemashu: pageCount, page: page });
    });
  });
});

router.get("/add", function (req, res, next) {
    res.render("product/productadd");
});

router.post("/doAdd", function (req, res, next) {
    const form = new multiparty.Form();
    // 上传图片的保存地址
    form.uploadDir = "public/upload"; // 上传的图片保存在 public 文件夹中
    // files 为图片上传成功返回的地址信息，fields 为获取的表单数据
    form.parse(req, function (err, fields, files) {
        // 获取提交的商品名、价格等数据以及图片上传成功后返回的信息
        const title = fields.title[0];
        console.log(title);
        const cat_id = fields.cat_id[0];
        const price = fields.price[0];
        const description = fields.description[0];
        const keywords = fields.keywords[0];
        const add_time = new Date();
        // 去掉 public/，默认情况下会自动到 public 文件夹中找静态资源文件夹
        const pic = files.pic[0].path.substr(7);
        console.log(pic);
        var sql = 'insert into product(name,cat_id,price,content,image,add_time,keywords) values(?,?,?,?,?,?,?)';
        var sqlParam = [title, cat_id, price, description, pic, add_time, keywords];
        db.conn.query(sql, sqlParam, function (err, result) {
            if (err) {
                console.log('[SELECT ERROR] - ', err.message);
                return;
            }
            res.redirect("/admin/product");
        });
    });
});

router.get("/search", function (req, res, next) { // 搜索商品列表
    var key = req.query.key; // 获取文本框输入
    var strSQL = "select * from product where name like ? order by id desc";
    var strParam = ['%' + key + '%']; // 模糊查询
    db.conn.query(strSQL, strParam, function (err, result) {
        if (err) {
            console.log('[SELECT ERROR] - ', err.message);
            return;
        }
        // 不再显示页码
        res.render("product/index", { list: result, page: -1, yemashu: -1 });
    });
});

router.get("/edit", function (req, res, next) {
    const id = req.query.id;
    var sql = 'select * from product where id=?';
    var sqlParam = [id];
    db.conn.query(sql, sqlParam, function (err, result) {
        if (err) {
            console.log('[SELECT ERROR] - ', err.message);
            return;
        }
        res.render("product/productedit", { item: result[0] });
    });
});

router.post("/doEdit", function (req, res, next) {
    const form = new multiparty.Form();
    form.uploadDir = "public/upload";
    form.parse(req, function (err, fields, files) {
        const id = fields._id[0];
        console.log(id);
        const title = fields.title[0];
        const cat_id = fields.cat_id[0];
        const price = fields.price[0];
        const description = fields.description[0];
        const keywords = fields.keywords[0];
        const originalFilename = files.pic[0].originalFilename; // 取原始文件名
        console.log(originalFilename);
        // 去掉 public/，默认情况下会自动到 public 文件夹中找静态资源文件夹
        const pic = files.pic[0].path.substr(7);
        console.log(pic);
        // originalFilename 有值，表示修改了图片
        // originalFilename 无值，表示未修改图片
        console.log(originalFilename.length); // 上传图片时，长度大于0，否则为0
        if (originalFilename.length > 0) {
            // 有修改图片，图片信息为：upload\b2mEBgtaeFwnrAmNHwj4EBF.jpg
            var sql = 'update product set name=?,cat_id=?,price=?,content=?,image=?,keywords=? where id=?';
            var sqlParam = [title, cat_id, price, description, pic, keywords, id];
        } else {
            // 未修改图片
            var sql = 'update product set name=?,cat_id=?,price=?,content=?,keywords=? where id=?';
            var sqlParam = [title, cat_id, price, description, keywords, id];
        }
        console.log(sqlParam);
        db.conn.query(sql, sqlParam, function (err, result) {
            if (err) {
                console.log('[SELECT ERROR] - ', err.message);
                return;
            }
            res.redirect("/admin/product");
        });
    });
});
module.exports = router;